﻿using BaseFrame.Entity;
using BaseFrame.Tool;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WORKALERT;

namespace BaseFrame
{
    public partial class Form1 : BaseForm
    {

        private Task _task;
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            //var list = sqlSugarClientOperation.GetCilentDb<ShopListInfoEntity>().GetList(f => 1 == 1);
            //var dd = "";
            //sqlSugarClientOperation.GetCilentDb<ShopListInfoEntity>().AsQueryable()
            //sqlSugarClientOperation.GetCilentDb<ShopListInfoEntity>().AsQueryable().Where()
            //var warite = Global.warite;
            //var add = 1 + 1;
            //var listdata = Global.sqlSugarClient.GetCilentDb<ShopListInfoEntity>().GetList();
            //var listdata1 = Global.sqlSugarClient.GetCilentDb<ShopListInfoEntity>().GetList();
            //ShopListInfoEntity shop = new ShopListInfoEntity() {
            //    Name = "名称",
            //    isAccomplishNavDetail = true,
            //    DetailNavUrl = "http://www.baidu.com"
            //};
            //Global.sqlSugarClient.GetCilentDb<ShopListInfoEntity>().Insert(shop);
            //var listdata111 = Global.sqlSugarClient.GetListDataByDynamic("shopListInfo", "Id=@Id AND isAccomplishNavDetail=@isAccomplishNavDetail", new { Id=1, isAccomplishNavDetail=true });
            //var list = Global.sqlSugarClient.GetListDataByJsonConditional<ShopListInfoEntity>(@"[{'FieldName':'Id','ConditionalType':0,'FieldValue':'2'}]");
            //List<string> excludelist = new List<string>() { "详细页导航" };
            //var propertysDescriptList = Global.sqlSugarClient.GetPropertyListDescrity<ShopListInfoEntity>();

            //    List<OperateInfoEntity> list = new List<OperateInfoEntity>(){
            //        new OperateInfoEntity() { operate_time =DateTime.Now},
            //        new OperateInfoEntity() { operate_time =DateTime.Now.AddMonths(2)  },
            //        new OperateInfoEntity() { operate_time =DateTime.Now.AddMonths(2)  },
            //        new OperateInfoEntity() { operate_time =DateTime.Now.AddMonths(3)  },
            //        new OperateInfoEntity() { operate_time =DateTime.Now.AddMonths(5)  },
            //};
            //    Global.sqlSugarClient.GetCilentDb<OperateInfoEntity>().InsertRange(list);
            //var liststate = Global.sqlSugarClient.GetYearGroupMonthStatistics();
            //var listdaysState = Global.sqlSugarClient.GetMonthGroupDayStatistics(DateTime.Now.AddMonths(-1));
            //批量插入数据
            //    List<ShopListInfoEntity> list = new List<ShopListInfoEntity>(){
            //           new ShopListInfoEntity() {
            //        Name = "名称44",
            //        isAccomplishNavDetail = false,
            //        DetailNavUrl = "http://www.toabao.com"
            //    },
            //           new ShopListInfoEntity() {
            //        Name = "名称55",
            //        isAccomplishNavDetail = true,
            //        DetailNavUrl = "http://www.baidu.com"
            //    },
            //           new ShopListInfoEntity() {
            //        Name = "名称66",
            //        isAccomplishNavDetail = false,
            //        DetailNavUrl = "http://www.tall.com"
            //    }
            //};
            //var result = Global.sqlSugarClient.InsertListReturnInsertCount(list);//返回插入行
            //var shopEntity = new ShopListInfoEntity()
            //{
            //    Name = "名称66",
            //    isAccomplishNavDetail = false,
            //    DetailNavUrl = "http://www.tall.com"
            //};
            //var mainId = Global.sqlSugarClient.InsertEntityReturnIdentity(shopEntity);
            //List<ShopListInfoEntity> shopListInfoEntities = new List<ShopListInfoEntity>();
            //for (int i = 0; i < 3000000; i++)
            //{
            //    var shopEntity = new ShopListInfoEntity()
            //    {
            //        Name = $"名称{i}",
            //        isAccomplishNavDetail = false,
            //        DetailNavUrl = "http://www.tall.com"
            //    };
            //    shopListInfoEntities.Add(shopEntity);
            //}
            //var successCount = Global.sqlSugarClient.InsertListBagData(shopListInfoEntities);//1w条以上的数据插入，超级快
            // Console.WriteLine(successCount);
            //Global.sqlSugarClient.InsertList(list);
            //Console.WriteLine(result);
            //var warite = Global.warite;

            //设置Grid的列
            var propertysDescriptList = Global.sqlSugarClient.GetPropertyListDescrity<ShopListInfoEntity>();
            BindGridDataColumn(propertysDescriptList, this.gridView1);
            //var list = Global.sqlSugarClient.GetList<ShopListInfoEntity>();
            //gridControl1.DataSource = list;

            AddPageUserControl(panel1, gridView1, gridControl1, myPagerEvents);
        }


        /// <summary>
        /// 执行分页
        /// </summary>
        /// <param name="curPage">当前页</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="mgncPager">分页控件</param>
        private void myPagerEvents(int curPage, int pageSize, MgncPager mgncPager)
        {
            if (_task != null && !_task.Status.Equals(TaskStatus.RanToCompletion))//这个操作得理解
                return;
            _task = new Task(() =>
            {
                BindData(curPage, pageSize, mgncPager);//条件查询 灵活绑定数据
            });
            _task.Start();
        }
        /// <summary>
        /// 查询数据+绑定数据
        /// </summary>
        /// <param name="curPage">当前页</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="mgncPager">分页控件</param>
        private void BindData(int curPage, int pageSize, MgncPager mgncPager)
        {
            #region 此处自定义查询+分页处理
            PageModel pageModel = new PageModel()
            {
                PageIndex = curPage,
                PageSize = pageSize
            };
            //var data = Global.sqlSugarClient.GetListPage<ShopListInfoEntity>(_conModels,curPage, pageSize, ref _allcount);
            //var data1 = Global.sqlSugarClient.GetListPage<ShopListInfoEntity>(f=>f.isAccomplishNavDetail==true,curPage, pageSize, ref _allcount);
            var data2 = Global.sqlSugarClient.GetListPage<ShopListInfoEntity>("Name like '%名称%'", curPage, pageSize, ref _allcount);
            mgncPager._gridControl1.DataSource = data2;
            _pageSize = pageSize;
            _curPage = curPage;
            mgncPager.RefreshPager(_pageSize, _allcount, _curPage);
            #endregion
            if (!isInitPage)
            {
                isInitPage = true;
                mgncPager._gridView1.BestFitColumns();
            }
            //var mgnc1Pager = panel1.Controls;
        }

        /// <summary>
        /// 配置Grid的Column属性
        /// </summary>
        /// <param name="propertysDescriptList">实体属性和描述</param>
        /// <param name="gridView">绑定的Grid</param>
        private void BindGridDataColumn(List<EntityDescriptBind> propertysDescriptList, GridView gridView)
        {
            SetProperty(gridView);
            for (int i = 0; i < propertysDescriptList.Count; i++)
            {
                var tempGridColumn = new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = propertysDescriptList[i].FieldDescription,
                    FieldName = propertysDescriptList[i].FieldName,
                    Name = $"gridColumn{i + 1}",
                    Visible = true,
                    VisibleIndex = i
                };
                gridView.Columns.Add(tempGridColumn);
            }
        }
        /// <summary>
        /// 设置相关属性
        /// </summary>
        /// <param name="gridView"></param>
        private void SetProperty(GridView gridView)
        {
            gridView.OptionsBehavior.Editable = false;//不可编辑
            gridView.OptionsView.ColumnAutoWidth = false;//关闭自动宽度设置
            gridView.OptionsView.ShowGroupPanel = false;//关闭显示组
        }

        /// <summary>
        /// 数据导出excel(包含了excel数据行超出的处理)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog
            {
                Description = "请选择导出数据所在文件夹"
            };
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                if (string.IsNullOrEmpty(dialog.SelectedPath))
                {
                    MessageBox.Show(this, "文件夹路径不能为空", "提示");
                    return;
                }
                else
                {
                    int pageIndex = 1;
                    var allcount = 0;
                    int ExcelExportpageSize = 500000;//每个excel文件中数据条数
                    var data = Global.sqlSugarClient.GetListPage<ShopListInfoEntity>(f => 1 == 1, pageIndex, ExcelExportpageSize, ref allcount);
                    if (allcount == 0)
                    {
                        MessageBox.Show("暂无要导出的数据");
                        return;
                    }
                    string fileName = dialog.SelectedPath + "\\平台数据.xlsx";
                    FileInfo newFile = new FileInfo(fileName);
                    if (newFile.Exists)
                    {
                        newFile.Delete();
                        newFile = new FileInfo(fileName);
                    }
                    var entityDescriptBinds = Global.sqlSugarClient.GetPropertyListDescrity<ShopListInfoEntity>();//获取导出数据描述（excel头）
                    string errorMsg = "";
                    EPPlusExcel.ExportData(data, entityDescriptBinds, newFile, ref errorMsg);
                    if (errorMsg.IsEmpty())
                    {
                        MessageBox.Show($"导出错误，错误信息：{errorMsg}");
                        return;
                    }
                    int pageNum = (int)Math.Ceiling(allcount / (double)ExcelExportpageSize);//计算总页数
                    for (int i = 1; i < pageNum; i++)
                    {
                        int tempPageIndex = i + 1;
                        new Task(() =>//利用多线程去导出每一页大量的数据（短时间导出海量数据处理），如果数据量太大，cpu性能不好不建议使用此方法，容易卡死，
                        {
                            data = Global.sqlSugarClient.GetListPage<ShopListInfoEntity>(f => 1 == 1, tempPageIndex, ExcelExportpageSize, ref allcount);
                            string tempFileName = dialog.SelectedPath + $"\\平台数据{pageIndex}.xlsx";
                            FileInfo tempNewFile = new FileInfo(tempFileName);
                            if (tempNewFile.Exists)
                            {
                                tempNewFile.Delete();
                                tempNewFile = new FileInfo(tempFileName);
                            }
                            EPPlusExcel.ExportData(data, entityDescriptBinds, tempNewFile, ref errorMsg);
                        }).Start();
                    }
                    MessageBox.Show("数据导出成功");
                }
            }
        }
    }
}
